package com.springboot.framework.service.impl;

import com.springboot.framework.dao.entity.UserCoupons;
import com.springboot.framework.dao.mapper.UserCouponsMapper;
import com.springboot.framework.enums.CouponsEnum;
import com.springboot.framework.enums.Errors;
import com.springboot.framework.enums.StatusEnum;
import com.springboot.framework.exception.BusinessException;
import com.springboot.framework.model.BuyerModel;
import com.springboot.framework.model.CouponsModel;
import com.springboot.framework.model.UserCouponsModel;
import com.springboot.framework.service.CouponsService;
import com.springboot.framework.service.UserCouponsService;
import com.springboot.framework.utils.DateUtil;
import com.springboot.framework.utils.MoneyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author SWF
 * @date 2019/6/20 11:22
 **/
@Service
public class UserCouponsServiceImpl implements UserCouponsService {

    @Resource
    private UserCouponsMapper userCouponsMapper;

    @Resource
    private CouponsService couponsService;

    /**
     * 领取优惠券
     *
     * @param buyerModel
     * @param couponsModel
     * @return
     */
    @Override
    public UserCouponsModel receive(BuyerModel buyerModel, CouponsModel couponsModel) {
        // 减库存
        couponsService.decreaseStock(couponsModel.getCouponsId());

        UserCoupons userCoupons = new UserCoupons();
        BeanUtils.copyProperties(couponsModel, userCoupons);
        // 数值类型转换
        userCoupons.setCouponsAmount((couponsModel.getCouponsAmount().multiply(new BigDecimal(100))).shortValue());
        if (couponsModel.getType().equals(CouponsEnum.TYPE_FIXED_DURATION.getCode())) {
            // 如果优惠券类型为固定时长
            Date date = new Date();
            userCoupons.setEffectiveDate(date);
            userCoupons.setCreateDate(date);
            userCoupons.setExpiryDate(DateUtil.addDateByHour(date, couponsModel.getEffectiveDuration()));
        }
        userCoupons.setUserId(buyerModel.getId());
        userCoupons.setUserWechatOpenid(buyerModel.getWechatOpenid());
        userCoupons.setStatus(CouponsEnum.STATUS_UNUSED.getCode());

        int resultCount = userCouponsMapper.insertSelective(userCoupons);
        if (resultCount == 0) {
            throw new BusinessException(Errors.COUPONS_RECEIVE_FAIL);
        }
        return convertUserCouponsModelFromUserCoupons(userCoupons);
    }

    /**
     * 查看所有优惠券，0失效  1可用/未生效  2已使用
     *
     * @param userId
     * @return
     */
    @Override
    public List<UserCouponsModel> list(Integer userId) {
        Example example = new Example(UserCoupons.class);
        example.and().andEqualTo("userId", userId)
                .andNotEqualTo("status", StatusEnum.DELETE.getCode());
        example.orderBy("createDate").desc();
        List<UserCoupons> userCoupons = userCouponsMapper.selectByExample(example);
        return convertUserCouponsModelFromUserCoupons(userCoupons);
    }

    /**
     * 查看未使用的优惠券
     *
     * @param userId
     * @return
     */
    @Override
    public List<UserCouponsModel> listOfUnused(Integer userId) {
        Example example = new Example(UserCoupons.class);
        example.and().andEqualTo("userId", userId)
                .andEqualTo("status", StatusEnum.NORMAL.getCode());
        example.orderBy("createDate").desc();
        List<UserCoupons> userCoupons = userCouponsMapper.selectByExample(example);
        return convertUserCouponsModelFromUserCoupons(userCoupons);
    }

    /**
     * 查看未使用的优惠券
     *
     * @param
     * @return
     */
    @Override
    public UserCouponsModel get(Integer userCouponsId) {
        Example example = new Example(UserCoupons.class);
        example.and().andEqualTo("userCouponsId", userCouponsId)
                .andEqualTo("status", CouponsEnum.STATUS_UNUSED.getCode());
        UserCoupons userCoupons = userCouponsMapper.selectOneByExample(example);
        return convertUserCouponsModelFromUserCoupons(userCoupons);
    }

    @Override
    public int getRecordCount(Integer userId, Integer couponsId) {
        Example example = new Example(UserCoupons.class);
        example.and().andEqualTo("userId", userId)
                .andEqualTo("couponsId", couponsId);
        return userCouponsMapper.selectCountByExample(example);
    }

    @Override
    public UserCouponsModel updateStatus(Integer userCouponsId, Byte status) {
        UserCoupons userCoupons = new UserCoupons();
        userCoupons.setUserCouponsId(userCouponsId);
        userCoupons.setStatus(status);
        userCouponsMapper.updateByPrimaryKeySelective(userCoupons);
        return null;
    }

    private UserCouponsModel convertUserCouponsModelFromUserCoupons(UserCoupons userCoupons) {
        if (userCoupons == null) {
            return null;
        }
        UserCouponsModel userCouponsModel = new UserCouponsModel();
        BeanUtils.copyProperties(userCoupons, userCouponsModel);
        // 数值类型转换
        userCouponsModel.setCouponsAmount(MoneyUtil.moneyFenToYuan(userCoupons.getCouponsAmount()));
        return userCouponsModel;
    }

    private List<UserCouponsModel> convertUserCouponsModelFromUserCoupons(List<UserCoupons> userCouponsList) {
        if (userCouponsList == null) {
            return null;
        }
        List<UserCouponsModel> userCouponsModelList = userCouponsList.stream()
                .map(e -> convertUserCouponsModelFromUserCoupons(e))
                .collect(Collectors.toList());
        return userCouponsModelList;
    }
}
